package com.ekuaitu.kuaitu.fragment;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.ekuaitu.kuaitu.R;
import com.ekuaitu.kuaitu.activity.BikeInUseRedActivity;
import com.ekuaitu.kuaitu.activity.BikeOrderDetailActivity;
import com.ekuaitu.kuaitu.activity.CarInUseActivity;
import com.ekuaitu.kuaitu.activity.CarOrderDetailActivity;
import com.ekuaitu.kuaitu.activity.LoginActivity;
import com.ekuaitu.kuaitu.activity.MainActivity;
import com.ekuaitu.kuaitu.adapter.MyRouteLvAdapter;
import com.ekuaitu.kuaitu.api.ApiStore;
import com.ekuaitu.kuaitu.api.UrlConstant;
import com.ekuaitu.kuaitu.bean.MyRouteBean;
import com.ekuaitu.kuaitu.utils.IntentKey;
import com.ekuaitu.kuaitu.utils.IntentUtils;
import com.ekuaitu.kuaitu.utils.MyApplication;
import com.ekuaitu.kuaitu.utils.TimeUtils;
import com.ekuaitu.kuaitu.utils.Toast.ToastCompat;
import com.ekuaitu.kuaitu.widget.MyListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyRouteShortFragment extends Fragment {


    @BindView(R.id.route_icon)
    ImageView routeIcon;
    @BindView(R.id.route_brand)
    TextView routeBrand;
    @BindView(R.id.route_id)
    TextView routeId;
    @BindView(R.id.route_time)
    TextView routeTime;
    @BindView(R.id.route_icon_start)
    ImageView routeIconStart;
    @BindView(R.id.route_tv_start)
    TextView routeTvStart;
    @BindView(R.id.route_icon_end)
    ImageView routeIconEnd;
    @BindView(R.id.route_tv_end)
    TextView routeTvEnd;
    @BindView(R.id.route_usedTime)
    TextView routeUsedTime;
    @BindView(R.id.route_iv_way)
    ImageView routeIvWay;
    @BindView(R.id.route_unDone)
    AutoLinearLayout routeUnDone;
    @BindView(R.id.route_lv)
    MyListView routeLv;
    @BindView(R.id.no_order)
    ImageView noOrder;
    @BindView(R.id.layout_noRoute)
    AutoRelativeLayout layoutNoRoute;
    @BindView(R.id.route_sv)
    PullToRefreshScrollView routeSv;
    @BindView(R.id.route_ll_unDone)
    AutoLinearLayout routeLlUnDone;
    @BindView(R.id.progress_bar_myRoute)
    RelativeLayout progressBarMyRoute;
    @BindView(R.id.route_ll_Done)
    AutoLinearLayout routeLlDone;
    @BindView(R.id.route_tv_status)
    TextView routeTvStatus;
    @BindView(R.id.no_order_rent)
    TextView noOrderRent;

    private Context mContext;
    public int curPage = 1;
    public String type = "";
    private List<MyRouteBean.AttachmentBean.NoCompleteOrderListBean> totalList0;
    public List<MyRouteBean.AttachmentBean.CompleteOrderlListBean> totalList1;
    private MyRouteLvAdapter adapter;


    public MyRouteShortFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_my_route_short, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mContext = getContext();

        initView();

    }
    public void initView() {

        routeSv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                routeSv.onRefreshComplete();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                curPage++;
                loadNetworkData();
            }
        });
        totalList0 = new ArrayList<>();
        totalList1 = new ArrayList<>();
        loadNetworkData();
        adapter = new MyRouteLvAdapter(totalList1, mContext);
        routeLv.setAdapter(adapter);
        //listview的点击事件
        routeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MyRouteBean.AttachmentBean.CompleteOrderlListBean item = totalList1.get(i);
                int type = item.getBusinessType();
                if (type == 1) {
                    Intent intent1 = new Intent(mContext, CarOrderDetailActivity.class);
                    intent1.putExtra(IntentKey.INTENT_ORDER_ID, item.getId());
                    startActivity(intent1);
                } else if (type == 2) {
                    Intent intent2 = new Intent(mContext, BikeOrderDetailActivity.class);
                    intent2.putExtra(IntentKey.INTENT_ORDER_ID, item.getId());
                    startActivity(intent2);
                }
            }
        });
    }
    public void loadNetworkData() {
        progressBarMyRoute.setVisibility(View.VISIBLE);
        if (MyApplication.getInstance().getUid() == null || MyApplication.getInstance().getUid().equals("")) {
            ToastCompat.makeText(mContext, getResources().getString(R.string.account_expire), Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            return;
        }
        ApiStore.getInstance().getApiService(UrlConstant.Request.BASE_URL).getOrderList(MyApplication.getInstance().getRequestFieldMap(),curPage + "", "10", type)
                .enqueue(new Callback<MyRouteBean>() {
                    @Override
                    public void onResponse(Call<MyRouteBean> call, Response<MyRouteBean> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            if (response.body().getStatus() == 200) {
                                progressBarMyRoute.setVisibility(View.GONE);
                                MyRouteBean.AttachmentBean result = response.body().getAttachment();
                                List<MyRouteBean.AttachmentBean.NoCompleteOrderListBean> list0 = result.getNoCompleteOrderList();
                                List<MyRouteBean.AttachmentBean.CompleteOrderlListBean> list1 = result.getCompleteOrderlList();
                                if (curPage == 1) {
                                    if (list0 != null && list0.size() != 0) {
                                        routeUnDone.setVisibility(View.VISIBLE);
                                        routeLlUnDone.setVisibility(View.VISIBLE);
                                        final MyRouteBean.AttachmentBean.NoCompleteOrderListBean item = list0.get(0);
                                        //未完成的点击事件：
                                        routeUnDone.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                int orderStatus = item.getStatus();
                                                switch (orderStatus) {
                                                    //0:"待取车",10:"进行中",15:"未支付",101:"已完成",102:"您已取消",104:"客服取消"
                                                    //<=15的在上面，>15在上面//16：手动取消有费用。17：自动取消有费用
                                                    case 15:
                                                    case 16:
                                                    case 17:
                                                        if (item.getBusinessType() == 1) {
                                                            IntentUtils.toSettlementActivity(mContext, item.getId(), "");
                                                        } else if (item.getBusinessType() == 2) {
                                                            IntentUtils.toSettlementActivity(mContext, item.getId(), item.getBikeModel().getBikeId());
                                                        }
                                                        break;
                                                    case 0:
                                                        break;
                                                    case 10:
                                                        if (item.getBusinessType() == 1) {
                                                            Intent intent1 = new Intent(mContext, CarInUseActivity.class);
                                                            intent1.putExtra(IntentKey.INTENT_ORDER_ID, item.getId());
                                                            startActivity(intent1);
                                                            getActivity().finish();
                                                        } else if (item.getBusinessType() == 2) {
                                                            Intent intent3 = new Intent(mContext, BikeInUseRedActivity.class);//BikeInUseActivity
                                                            intent3.putExtra(IntentKey.INTENT_ORDER_ID, item.getId());
                                                            startActivity(intent3);
                                                            getActivity().finish();
                                                        }
                                                        break;
                                                    case 101:
                                                        break;
                                                    case 102:
                                                        break;
                                                    case 103:
                                                        break;
                                                    case 104:
                                                        break;
                                                }
                                            }
                                        });
                                        //订单状态
                                        routeTvStatus.setText(getOrderStatus(item.getStatus()));
                                        //订单时间
                                        routeTime.setText(TimeUtils.getFormatDate(item.getOrderTime() + "", "M月d日H:mm"));
                                        //耗时
                                        if (item.getBusinessType() == 1 && (item.getStatus() == 17 || item.getStatus() == 103)) {
                                            routeUsedTime.setText("耗时：15分钟");
                                        } else {
                                            routeUsedTime.setText("耗时：" + TimeUtils.formatMinPlusOne((item.getEndBillingTime() - item.getStartBillingTime()) / 1000 + ""));
                                        }
                                        if (item.getBusinessType() == 1 && item.getCarModel() != null) {
                                            //汽车图标
                                            routeIvWay.setImageResource(R.drawable.icon_car);
                                            //汽车品牌
                                            if (item.getCarModel().getBrand() != null && item.getCarModel().getModel() != null) {
                                                routeBrand.setText(item.getCarModel().getBrand() + item.getCarModel().getModel());
                                            }
                                            //汽车牌照
                                            if (item.getCarModel().getLicenseTag() != null) {
                                                routeId.setText(item.getCarModel().getLicenseTag());
                                            }
                                            //起点
                                            routeTvStart.setText(item.getOnLocationName());
                                            //终点
                                            if (item.getDownLocationName() != null) {
                                                routeTvEnd.setText(item.getDownLocationName());
                                            }
                                        } else if (item.getBusinessType() == 2 && item.getBikeModel() != null) {
                                            //单车图标
                                            routeIvWay.setImageResource(R.drawable.icon_bicycle);
                                            //单车无品牌
                                            routeBrand.setText("");
                                            //单车编号
                                            if (item.getBikeModel().getLicenseTag() != null) {
                                                routeId.setText(item.getBikeModel().getLicenseTag());
                                            }
                                            //单车起点和终点
                                            routeTvStart.setText(item.getOnLocationName());
                                            routeTvEnd.setText(item.getDownLocationName());
                                        }

                                        totalList1.addAll(list1);
                                        adapter.notifyDataSetChanged();
                                        routeSv.onRefreshComplete();

                                    } else {
                                        routeUnDone.setVisibility(View.GONE);
                                        routeLlUnDone.setVisibility(View.GONE);
                                        if (list1 == null || list1.size() == 0) {

                                            layoutNoRoute.setVisibility(View.VISIBLE);
                                            routeLlDone.setVisibility(View.GONE);
                                            routeLv.setVisibility(View.GONE);
                                            routeSv.onRefreshComplete();

                                        } else {
                                            layoutNoRoute.setVisibility(View.GONE);
                                            routeLlDone.setVisibility(View.VISIBLE);
                                            routeLv.setVisibility(View.VISIBLE);
                                            totalList1.addAll(list1);
                                            adapter.notifyDataSetChanged();
                                            routeSv.onRefreshComplete();
                                        }
                                    }
                                } else {
                                    totalList1.addAll(list1);
                                    adapter.notifyDataSetChanged();
                                    routeSv.onRefreshComplete();
                                }
                            } else {
                                ToastCompat.makeText(mContext, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            ToastCompat.makeText(mContext, getResources().getString(R.string.serverError), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<MyRouteBean> call, Throwable t) {
                        routeSv.onRefreshComplete();
                        progressBarMyRoute.setVisibility(View.GONE);
                        ToastCompat.makeText(mContext, getResources().getString(R.string.badNetwork), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    @OnClick({R.id.no_order_rent, R.id.route_unDone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.no_order_rent:
                startActivity(new Intent(mContext, MainActivity.class));
                getActivity().finish();
                break;
            case R.id.route_unDone:
                break;
        }

    }

    public String getOrderStatus(int code) {
        String orderStatus = null;
        switch (code) {
            case 0:
                orderStatus = "未取车";
                break;
            case 10:
                orderStatus = "用车中";
                break;
            case 15:
            case 16:
            case 17:
                orderStatus = "未结算";
                break;
            case 101:
                orderStatus = "已完成";
                break;
            case 102:
                orderStatus = "手动取消";
                break;
            case 103:
                orderStatus = "自动取消";
                break;
            case 104:
                orderStatus = "客服取消";
                break;
        }
        return orderStatus;
    }

    @Override
    public void onResume() {
        super.onResume();
        routeLv.setFocusable(false);
    }
}
